'''
requests的代理设置
'''
# import asyncio
# import time
# import requests
# headers = {
#     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
# }
# proxy = '106.111.223.132:40017'
# proxies = {
#     'http': 'http://' + proxy,
#     'https': 'http://' + proxy
# }
# try:
#     res = requests.get('https://www.baidu.com', proxies=proxies, headers=headers)
#     print(res.status_code)
# except requests.exceptions.ConnectionError as e:
#     print('Error', e.args)


# 使用SOCKS类型代理
# 需要先安装包requests[socks]
# import requests
# proxy = '113.229.61.136:40024'
# proxies = {
#     'http': 'socks5://' + proxy,
#     'https': 'socks5://' + proxy
# }
# try:
#     res = requests.get('https://www.httpbin.org/get', proxies=proxies)
#     print(res.text)
# except requests.exceptions.ConnectionError as e:
#     print('Error', e.args)

# 使用socks模块设置socks代理
# 需要安装socks库
# import socks
# import socket
# import requests
# socks.set_default_proxy(socks.SOCKS5, '211.93.121.177', 40002)
# socket.socket = socks.socksocket
# try:
#     res = requests.get('https://www.httpbin.org/get')
#     print(res.text)
# except requests.exceptions.ConnectionError as e:
#     print('Error', e.args)

'''
httpx的代理设置
'''
# import httpx
# proxy = '211.93.121.177:40002'
# proxies = {
#     'http://': 'http://' + proxy,
#     'https://': 'http://' + proxy
# }
# with httpx.Client(proxies=proxies) as client:
#     res = client.get('https://www.httpbin.org/get')
#     print(res.text)

# httpx的SOCKS代理
# 需要安装httpx-socks[asyncio]库，安装命令pip install "httpx-socks[asyncio]"
# 需要设置同步模式或异步模式
# 同步模式
# import httpx
# from httpx_socks import SyncProxyTransport
# transport = SyncProxyTransport.from_url('socks5://125.87.84.231:40039')
# with httpx.Client(transport=transport) as client:
#     res = client.get('https://www.httpbin.org/get')
#     print(res.text)
#
# # 异步模式
# # import httpx
# from httpx_socks import AsyncProxyTransport
# transport = AsyncProxyTransport.from_url('socks5://125.87.84.231:40039')
# async def main():
#     async with httpx.AsyncClient(transport=transport) as client:
#         res = await client.get('https://www.httpbin.org/get')
#         print(res.text)
# if __name__ == '__main__':
#     asyncio.run(main())

'''
Selenium的代理设置
'''
# from selenium import webdriver
# from selenium.webdriver.chrome.service import Service
# driver_path = 'D:\install\Python\Scripts\chromedriver.exe'
# proxy = '47.100.201.85:80'
# options = webdriver.ChromeOptions()
# options.add_argument('--proxy-server=http://' + proxy)
# browser = webdriver.Chrome(service=Service(driver_path), options=options)
# browser.get('https://www.httpbin.org/get')
# print(browser.page_source)
# browser.close()

# 代理需要认证的设置方法
# 在本地创建一个manifest.json配置文件和background.js脚本设置认证代理，运行代码后，本地后生成一个proxy_auth_plugin.zip文件来保存当前的配置
# 需要注意，在manifest.json文件中，书中background值为{"scripts": ["background.js"]}需要改为{"service_worker": "background.js"}，否则会报错
# from selenium import webdriver
# from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.chrome.service import Service
# import zipfile
# ip = '127.0.0.1'
# port = 7890
# username = 'foo'
# password = 'bar'
# manifest_json = """{
#     "version":"1.0.0",
#     "manifest_version":3,
#     "name":"Chrome Proxy",
#     "permissions":[
#         "proxy",
#         "tabs",
#         "unlimitedStorage",
#         "storage",
#         "<all_urls>",
#         "webRequest",
#         "webRequestBlocking"
#         ],
#     "background":{
#             "service_worker": "background.js"
#             }
# }
# """
# background_js = """
# var config = {
#     mode: "fixed_servers",
#     rules: {
#         singleProxy: {
#             scheme: "http",
#             host: "%(ip)s",
#             port: %(port)s
#         }
#     }
# }
# chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
#
# function callbackFn(details) {
#     return {
#         authCredentials: {username: "%(username)s",
#             password: "%(password)s"
#         }
#     }
# }
# chrome.webRequest.onAuthRequired.addListener(
#     callbackFn,{urls: ["<all_urls>"]},['blocking'])
# """ % {'ip': ip, 'port': port, 'username': username, 'password': password}
#
# plugin_file = 'proxy_auth_plugin.zip'
# with zipfile.ZipFile(plugin_file, 'w') as zp:
#     zp.writestr("manifest.json", manifest_json)
#     zp.writestr("background.js", background_js)
# options = Options()
# options.add_argument("--start-maximized")
# options.add_extension(plugin_file)
# driver_path = 'D:\install\Python\Scripts\chromedriver.exe'
# browser = webdriver.Chrome(options=options,service=Service(driver_path))
# browser.get('https://www.httpbin.org/get')
# print(browser.page_source)
# browser.close()

# selenium的SOCKS代理
# from selenium import webdriver
# proxy = '127.0.0.1:40002'
# options = webdriver.ChromeOptions()
# options.add_argument('--proxy-server=socks5://' + proxy)
# browser = webdriver.Chrome(options=options)
# browser.get('https://www.httpbin.org/get')
# print(browser.page_source)
# browser.close()


'''
aiohttp的代理
'''
# import asyncio
# import aiohttp
# proxy = 'http://127.0.0.1:7890'
# async def main():
#     async with aiohttp.ClientSession() as session:
#         async with session.get('https://www.httpbin.org/get', proxy=proxy) as res:
#             print(await res.text())
# if __name__ == '__main__':
#     asyncio.run(main())
# 如果需要认证，就把代理地址改为：http://username:password@127.0.0.1:7890

# aiohttp的SOCKS代理
# 需要安装一个支持库aiohttp-socks，安装命令pip install aiohttp-socks
# import asyncio
# import aiohttp
# from aiohttp_socks import ProxyConnector
# connector = ProxyConnector.from_url('socks5://127.0.0.1:7890')
# async def main():
#     async with aiohttp.ClientSession(connector=connector) as session:
#         async with session.get('https://www.httpbin.org/get') as res:
#             print(await res.text())
# if __name__ == '__main__':
#     asyncio.run(main())


'''
Pyppeteer的代理
'''
# import asyncio
# from pyppeteer import launch
# proxy = '127.0.0.1:7890'
# async def main():
#     browser = await launch({'args': ['--proxy-server=http://' + proxy], 'headless': False})
#     page = await browser.newPage()
#     await page.goto('https://www.httpbin.org/get')
#     print(await page.content())
#     await browser.close()
# if __name__ == '__main__':
#     asyncio.run(main())

# Pyppeteer的SOCKS代理
# import asyncio
# from pyppeteer import launch
# proxy = '127.0.0.1:7890'
# async def main():
#     browser = await launch({'args': ['--proxy-server=socks5://' + proxy], 'headless': False})
#     page = await browser.newPage()
#     await page.goto('https://www.httpbin.org/get')
#     print(await page.content())
#     await browser.close()
# if __name__ == '__main__':
#     asyncio.run(main())


'''
Playwright的代理设置
'''
# from playwright.sync_api import sync_playwright
# with sync_playwright() as p:
#     browser = p.chromium.launch(proxy={
#         'server': 'http://127.0.0.1:7890'
#     })
#     page = browser.new_page()
#     page.goto('https://www.httpbin.org/get')
#     print(page.content())
#     browser.close()

# Playwright的SOCKS代理
# from playwright.sync_api import sync_playwright
# with sync_playwright() as p:
#     browser = p.chromium.launch(proxy={
#         'server': 'socks5://127.0.0.1:7890'
#     })
#     page = browser.new_page()
#     page.goto('https://www.httpbin.org/get')
#     print(page.content())
#     browser.close()

# 需要认证的代理，在proxy参数中额外设置username和password参数
# from playwright.sync_api import sync_playwright
# with sync_playwright() as p:
#     browser = p.chromium.launch(proxy={
#         'server': 'http://127.0.0.1:7890',
#         'username': 'foo',
#         'password': 'bar'
#     })
#     page = browser.new_page()
#     page.goto('https://www.httpbin.org/get')
#     print(page.content())
#     browser.close()

